
import 'package:boss/main.dart';
import 'package:boss/ui/widget/loading/loading.dart';
import 'package:hi_common/hi_common.dart';
import 'package:flutter/material.dart';
import 'package:async/async.dart';
import 'package:flustars/flustars.dart' as flustars;

class UnitProvider extends ChangeNotifier {
  List<String> units = [];

  Future<Result<List<String>>> queryUnit() async {
    if (units.isNotEmpty) return Result.value(units);

    final res = await api.queryStoreCommodityUnitInfo();
    if (!res.successful()) {
      return Result.error(res.msg);
    }

    final data = (res.data as String).split('|').where((element) => !flustars.TextUtil.isEmpty(element)).toList();

    if (data.isNotEmpty) {
      units = data;
      notifyListeners();
    }

    return Result.value(units);
  }

  Future<bool> updateUnit(List<String> units) async {
    showLoadingToast();
    final res = await api.updateCommodityUnit({'unitParams': units.join('|')});
    if (!res.successful()) {
      toast(res.msg);
      hideLoadingToast();
      return false;
    }

    hideLoadingToast();

    this.units = units;
    notifyListeners();
    return true;
  }
}
